﻿using JshRCSWebApi.Infrastructure;
using JshRCSWebApi.Service.ToolService;
using JshRCSWebApi.SqlSugarDB.Model.jshrcs_initial;
using Microsoft.AspNetCore.Http;
using SqlSugar.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JshRCSWebApi.ServiceImpl.Tool
{
    public class ToolServiceImpl : ToolService
    {
        private readonly Repository<dynamic> _repository;
        private string uploadFolder = AppDomain.CurrentDomain.BaseDirectory + "/File/Uploads";
        public ToolServiceImpl(Repository<dynamic> repository) { 
            this._repository = repository;
        }

        /// <summary>
        /// 新增图片
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public async Task<ApiResult> UploadImage(IFormFile image)
        {
            if (image == null || image.Length == 0)
            {
                return await Task.Run(async () => ApiResult.Error("未选择文件"));
            }
            string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".svg", ".gif" };
            string fileExtension = Path.GetExtension(image.FileName).ToLowerInvariant();
            if (!allowedExtensions.Contains(fileExtension))  // 验证文件类型是否为允许的格式
            {
                return await Task.Run(async () => ApiResult.Error("上传图片格式不正确"));
            }
            long maxFileSizeInBytes = 3 * 1024 * 1024; // 验证文件大小是否在允许范围内 3MB
            if (image.Length > maxFileSizeInBytes)
            {
                return await Task.Run(async () => ApiResult.Error("上传的图片大小不能超过3MB"));
            }
            Directory.CreateDirectory(uploadFolder);  // 创建目标文件夹（如果不存在）
            string fileName = Path.GetFileNameWithoutExtension(image.FileName);    // 生成唯一的文件名
            string extension = Path.GetExtension(image.FileName);
            string uniqueFileName = $"{fileName}_{Path.GetRandomFileName()}{extension}";
            string filePath = Path.Combine(uploadFolder, uniqueFileName);
            string strFileUpLoad = uploadFolder.Substring(uploadFolder.IndexOf("/File/Uploads")); //截取"/File/Uploads"
            string resultPath = strFileUpLoad + $"/{uniqueFileName}";
            using (var stream = new FileStream(filePath, FileMode.Create))    // 保存文件到服务器
            {
                await image.CopyToAsync(stream);
            }
            if (File.Exists(filePath))
                // 文件上传成功
                return await Task.Run(async () => ApiResult.Success("上传成功", resultPath));
            else
                return await Task.Run(async () => ApiResult.Error("文件未保存到服务器"));
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteImageByID(long ID)
        {
            var siteInfo = _repository.Select<sitetype>(s => s.ID == ID);
            if (siteInfo == null)
                return await Task.Run(async () => ApiResult.Error("站点类型记录不存在"));
            string oldFilePath = siteInfo.stImage; // 查询原有的图片路径
            if (!string.IsNullOrEmpty(oldFilePath) && File.Exists(oldFilePath))
            {
                File.Delete(oldFilePath);  // 删除原有的图片
            }
            return await Task.Run(async () => !File.Exists(oldFilePath) ?
                        ApiResult.Success("删除图片成功") : ApiResult.Error("更新图片失败"));
        }
    }
}
